package com.sz.app.customer.api;

import com.sz.biz.app.dto.TokenDto;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.app.web.security.Des;
import com.sz.biz.common.utils.PassWordCreate;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.common.base.cache.redis.RedisPoolManager;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.core.service.sms.SmsService;
import com.sz.common.core.system.dto.SmsBodyDto;
import com.sz.app.customer.api.system.dto.RegisterEnterpriseDto;
import com.sz.app.customer.web.security.CustomerWebPrincipalManager;
import com.sz.app.customer.web.security.SecurityKeys;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * Created by xutao on 17/6/1.
 */
@RestController
@RequestMapping("${api}/user/register")
@Api(description = " ", tags = "002、注册")
public class RegisterUserController extends BaseController {

    public static final String REGISTER = "register";
    @Autowired
    private SecurityKeys securityKeys;

    @Autowired
    CustomerService customerService;

    @Autowired
    CustomerUserService customerUserService;

    @Autowired
    private SmsService smsService;

    @Autowired
    CustomerWebPrincipalManager principalManager;

    @Value("${sms.forgetpassword.authentication.code.timeout}")
    private int validateCodeTimeOut;

    @Value("${sms.register.authentication.templatekey}")
    private String templateKey;

    @Value("${sms.register.authentication.templatecode}")
    private String smsTemplateCode;

    /**
     * 注册企业账户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "注册企业账户", notes = "注册企业账户")
    @RequestMapping(value = "/baseinfo", method = {RequestMethod.POST})
    public ResultDto registerEnterpriseAccount(@RequestBody RegisterEnterpriseDto registerEnterpriseDto) throws Exception {

        String phoneNo = registerEnterpriseDto.getTelNo();
        registerEnterpriseDto.setCode(registerEnterpriseDto.getCode());
        registerEnterpriseDto.setTelNo(phoneNo);
        registerEnterpriseDto.setValidateCode(registerEnterpriseDto.getValidateCode());
        registerEnterpriseDto.setPassword(decPassword(registerEnterpriseDto.getPassword()));

        ResultDto resultDto = new ResultDto();


        Jedis jedis = RedisPoolManager.getJedis();
        String cacheValidateCode = jedis.get(phoneNo + "register");

        if (cacheValidateCode != null && cacheValidateCode.equals(registerEnterpriseDto.getValidateCode())) {
            Map<String,Object> map = customerService.registerEnterpriseAccount(registerEnterpriseDto.getUserName(),
                    registerEnterpriseDto.getCode(),registerEnterpriseDto.getTelNo(),registerEnterpriseDto.getPassword());

            jedis.del(registerEnterpriseDto.getTelNo() + "register");

            setupPrincipal(Integer.parseInt(String.valueOf(map.get("cususerid"))), registerEnterpriseDto.getUserName());
            TokenDto tokenDto = new TokenDto(registerEnterpriseDto.getUserName(), SecurityUtils.getSubject().getSession().getId().toString(),
                    SecurityUtils.getSubject().getSession().getTimeout());

            resultDto.setMsg("注册企业账户成功！");
            resultDto.setData(tokenDto);
        } else {

            resultDto.setMsg("Validate code error！");

            resultDto.setErrorCode(-1);
        }
        jedis.close();
        return resultDto;
    }

    private void setupPrincipal(int accountId,String accountName) {
        principalManager.setupPrincipal(AppDomain.CUSTOMER, accountId,accountName,null);
    }

    /**
     * 注册-短信发送验证码接口
     */
    @ApiOperation(value = "注册-短信发送验证码接口", notes = "注册-短信发送验证码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobilePhone", value = "手机号码",
                    required = true, dataType = "string", paramType = "query")})
    @RequestMapping(value = "/sendsmscode", method = {RequestMethod.GET})
    public QResultDto sendSmsValiateCode(@RequestParam String mobilePhone) {

        QResultDto qResultDto = new QResultDto();

        //生成手机验证码
        PassWordCreate pwc = new PassWordCreate();
        String validateCode = pwc.createValidateCode(6);

        //将验证码插入redis
        Jedis jedis = RedisPoolManager.getJedis();

        if(!jedis.exists(mobilePhone + REGISTER)) {

            jedis.set(mobilePhone + REGISTER, validateCode);
            jedis.expire(mobilePhone + REGISTER, validateCodeTimeOut);

            //组装短信内容进行发送
            SmsBodyDto smsBodyDto = new SmsBodyDto();

            String[] templateKeyArray = templateKey.split(",");

            for (int i=0; i<templateKeyArray.length; i++) {

                smsBodyDto.getSmsTemplateKey().add(templateKeyArray[i]);
            }

            smsBodyDto.getSmsTemplateValue().add(validateCode);

            smsService.sendSms(mobilePhone, smsTemplateCode, smsBodyDto);

        } else {

            qResultDto.setErrorCode(-1);
            qResultDto.setMsg("短信验证码已经发送，请稍后再试！");
        }

        jedis.close();

        return qResultDto;
    }
    /**
     * 异步检查验证码是否正确
     */
    @ApiOperation(value = "检查短信验证码", notes = "检查短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNo", value = "手机号码",
                    required = true, dataType = "string", paramType = "query"),@ApiImplicitParam(name = "validateCode",value = "验证码",required = true,dataType = "String",paramType = "query")})
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    public boolean checkCode(@RequestParam String validateCode,String phoneNo){
        Jedis jedis = RedisPoolManager.getJedis();
        String cacheValidateCode = jedis.get(phoneNo + REGISTER);
        jedis.close();
        if(cacheValidateCode.equals(validateCode)){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 异步检查编码是否已经存在
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "异步检查编码是否已经存在", notes = "异步检查编码是否已经存在")
    @RequestMapping(value = "/check/{code}", method = {RequestMethod.GET})
    public QResultDto checkCodeExist(@PathVariable String code) throws Exception {

        Boolean isExist = customerUserService.userNameIsExist(null,code);

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(isExist);

        return qResultDto;
    }

    private String decPassword(String password){
//        String key1 = "DAB019642892EC3231802E13447D3F52";
//        String key2 = "14833CB10FAF594B0874F3494AB0946E";
//        String key3 = "42099DDB28D27ADFCFD3E961BE6E08D5";
        if (StringUtils.isNotBlank(password)) {
            return Des.getDesTool().strDec(password, securityKeys.getSecurityKey1(), securityKeys.getSecurityKey2(), securityKeys.getSecurityKey3());
        }
        return password;
    }
}
